<?php

namespace App\Admin\Controllers;

use App\Models\ShopDish;
use App\Models\Shop;
use App\Models\ShopDishAttribute;
use App\Models\ShopMenu;
use Encore\Admin\Form;
use Encore\Admin\Grid;
use Encore\Admin\Facades\Admin;
use Encore\Admin\Layout\Content;
use App\Http\Controllers\Controller;
use Encore\Admin\Controllers\ModelForm;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Input;

class DishesController extends Controller
{
    use ModelForm;

    /**
     * Index interface.
     *
     * @return Content
     */
    public function index()
    {
        return Admin::content(function (Content $content) {

            $content->header('header');
            $content->description('description');

            $content->body($this->grid());
        });
    }

    /**
     * Edit interface.
     *
     * @param $id
     * @return Content
     */
    public function edit($id)
    {
        return Admin::content(function (Content $content) use ($id) {

            $content->header('header');
            $content->description('description');

            $content->body($this->form()->edit($id));
        });
    }

    /**
     * Create interface.
     *
     * @return Content
     */
    public function create()
    {
        return Admin::content(function (Content $content) {
            $content->header('header');
            $content->description('description');

            $content->body($this->form());
        });
    }

    public function newcreate()
    {
        return Admin::content(function (Content $content){
            $content->header('header');
            $content->description('description');

            $content->body($this->form());
        });
    }

    /*public function editform()
    {
        return Admin::content(function (Content $content) {

            $content->header('修改菜式');
            $content->description('');
            $content->breadcrumb(
                ['text' => '菜式管理', 'url' => '/shop/dishes'],
                ['text' => '']
            );
            $content->body($this->form()->edit(\request('dish_id')));
        });
    }*/

    /**
     * Make a grid builder.
     *
     * @return Grid
     */
    protected function grid()
    {
        return Admin::grid(ShopDish::class, function (Grid $grid) {
            //$grid->disableActions();
            $grid->disableCreateButton();//禁用新增
            $grid->filter(function($filter){
                // 去掉默认的id过滤器
                $filter->disableIdFilter();
                $filter->like('shop.shop_name', '商铺名');
                $filter->like('shop_menu.menu_name', '菜单分类');
                $filter->like('dishes_name', '菜名');
                $filter->equal('is_attr','是否多规格')->radio([
                    0    => '否',
                    1    => '是',
                ]);
            });
            if(request('shop_id')!=''){
                $grid->model()->where('shop_id',request('shop_id'));
            }
            $grid->id('ID')->sortable();
            $grid->column('shop.shop_name', '商铺名');
            $grid->column('shop_menu.menu_name', '菜单分类');
            $grid->column('dishes_name', '菜名');
            $grid->column('price', '价格');
            //$grid->column('discount', '折扣');
            //$grid->column('discount_price', '折后价');
            $grid->column('sales', '销量');
            $grid->is_attr('是否多规格')->display(function ($is_attr){
                if($is_attr == 1){
                    return '是';
                }else{
                    return '否';
                }
            });
            $grid->thumb('图片')->image(env("APP_URL"), 100, 100);
            $grid->created_at();
            $grid->updated_at();
            /*$grid->actions(function ($actions) {
                $actions->disableEdit();
                $dish_id = $actions->getKey();
                $actions->prepend('<a href="/admin/shop/editdishes?dish_id='.$dish_id.'"><i class="fa fa-eye">修改菜式</i></a>');
            });*/
        });
    }

    /**
     * Make a form builder.
     *
     * @return Form
     */
    protected function form()
    {
        return Admin::form(ShopDish::class, function (Form $form) {
            $form->saving(function (Form $form) {
                /*if($form->menu_id==null){
                    echo "<script> alert('请选择菜式分类！');history.back(); </script>";die;
                }
                //多规格
                $attribute = $form->dishattribute;
                if ($attribute){
                    $data = array();
                    foreach ($attribute as $key => $value) {
                        $data[] = $value;
                    }
                    for ($i = 0; $i < count($data); $i++) {
                        if (empty($data[$i]['attribute'])) {
                            echo "<script> alert('多规格错误，请刷新重试！');history.back(); </script>";
                            die;
                        }
                    }
                }
                if(count(request()->route()->parameters())==0) {
                    if ($form->is_attr == 'on') {
                        $form->is_attr = 1;
                    } else {
                        $form->is_attr = 0;
                    }*/
                /*$spec = '';
                for ($i = 1; $i < count($data); $i++) {
                    if(($data[$i]['name'] !='' && $data[$i]['spec'] =='') || ($data[$i]['name'] =='' && $data[$i]['spec'] !='')){
                        echo "<script> alert('规格属性不完整！');history.back(); </script>";die;
                    }
                    $spec .= $data[$i]['name'] . '|' . $data[$i]['spec'] . ',';
                }
                $spec = rtrim($spec, ",");
                $spec = explode(',|', $spec);*/
                /*//折后价
                $discount_price = $form->price * $form->discount;
                if($discount_price==0){
                    $discount_price = null;
                }*/

                /*DB::beginTransaction();
                 try {
                    $res = DB::table('shop_dishes')->insertGetId([
                        'shop_id' => request('shop_id'),
                        'menu_id' => $form->menu_id,
                        'dishes_name' => $form->dishes_name,
                        //'discount_price' => $discount_price,
                        'price' => $form->price,
                        'discount' => $form->discount,
                        'thumb' => $form->thumb,
                        'is_attr' => $form->is_attr,
                        'created_at' => date('Y-m-d H:i:s'),
                        'updated_at' => date('Y-m-d H:i:s')
                    ]);
                        if($attribute) {
                            for ($x = 0; $x < count($data); $x++) {
                                DB::table('shop_dish_attribute')
                                    ->insert([
                                        'dish_id' => $res,
                                        'attribute' => $data[$x]['attribute'],
                                        'spec' => $data[$x]['spec'],
                                        'created_at' => date('Y-m-d H:i:s'),
                                        'updated_at' => date('Y-m-d H:i:s')
                                    ]);
                            }
                        }
                    DB::commit();
                 }catch (\Exception $e){
                    DB::rollBack();
                    echo "<script> alert('添加菜式失败！');history.back(); </script>";die;
                 }
                    echo "<script> alert('添加菜式成功！');history.back(); </script>";die;*/
                // }
            });
            $form->saved(function (Form $form) {
                $shopdish = ShopDish::find($form->model()->id);
                if($shopdish->thumb && $form->thumb) {
                    ShopDish::where('id', $form->model()->id)->update(['thumb' => '/storage/' . $shopdish->thumb]);
                }
                if($form->dishattribute){
                    ShopDish::where('id', $form->model()->id)->update(['is_attr' => 1]);
                }
                if(request()->route()->parameters()) {
                    echo '<script>alert("保存成功");history.go(-2);</script>';
                    die;
                }else{
                    echo '<script>alert("保存成功");history.back();</script>';
                    die;
                }
            });
            //$form->display('id', 'ID');
            $form->text('shop_id', '店铺id')->value(request('shop_id'));
            if(request('shop_id')) {
                $shop_name = Shop::where('id', request('shop_id'))->first()->shop_name;
                $form->display('shop.shop_name', '店铺名')->default($shop_name);
            }else{
                $form->display('shop.shop_name', '店铺名');
            }
            $form->text('dishes_name', '菜名')->rules('required');
            $form->text('price', '价格')->rules('required');
            if(request('shop_id')) {
                $ShopMenu = ShopMenu::where('shop_id', request('shop_id'))->select('id', 'menu_name')->get()->toArray();
            }else{
                $shop = ShopDish::find(request()->route()->parameters()['dish']);
                $ShopMenu = ShopMenu::where('shop_id', $shop->shop_id)->select('id', 'menu_name')->get()->toArray();
            }
            $res = array();
            foreach ($ShopMenu as $key => $value) {
                $res[$value['id']] = $value['menu_name'];
            }
            $form->select('menu_id', '菜式分类')->options($res)->rules('required');
            /*if(request()->route()->parameters()) {
                $ShopDishAttribute = ShopDishAttribute::where('dish_id', request()->route()->parameters())->first();
                if ($ShopDishAttribute) {
                    $is_attr = [
                        'on' => ['value' => 1, 'text' => '是', 'color' => 'primary'],
                        'off' => ['value' => 0, 'text' => '否', 'color' => 'default'],
                    ];
                    $form->switch('is_attr', '是否多规格')->states($is_attr);
                }
            }*/

            $form->hasMany("dishattribute", "多规格",function ($form) {
                $form->text('attribute', '规格名称');
                $form->text('spec', '规格');
            });
            //$form->text('discount', '折扣');

            /*$status = [
                'on' => ['value' => 1, 'text' => '上架', 'color' => 'primary'],
                'off'  => ['value' => 0, 'text' => '下架', 'color' => 'default'],
            ];
            $form->switch('status', '上下架')->states($status);*/
            //$form->select('status', '上下架')->options([0 => '否', 1 => '是'])->default('1');
            $form->radio('status', '上下架')->options(['1' => '上架', '0'=> '下架'])->default('1');
            if(request('shop_id')){
                $user_id = Shop::where('id',request('shop_id'))->first()->user_id;
            }else{
                $shop_id = ShopDish::find(request()->route()->parameters()['dish'])->shop_id;
                $user_id = Shop::where('id',$shop_id)->first()->user_id;
            }

            $form->image('thumb', '图片')->move("user_$user_id/info")->uniqueName()->rules('required');

            $form->display('created_at', 'Created At');
            $form->display('updated_at', 'Updated At');
        });
    }

    protected function newform()
    {
        return Admin::form(ShopDish::class, function (Form $form) {

            $form->text('shop_id', '店铺id')->value(request('shop_id'));
            $shop_name = Shop::where('id',request('shop_id'))->first()->shop_name;
            $form->display('shop.shop_name', '店铺名')->default($shop_name);
            $form->text('dishes_name', '菜名')->rules('required');
            $form->text('price', '价格')->rules('required');

            $ShopMenu = ShopMenu::where('shop_id', request('shop_id'))->select('id', 'menu_name')->get()->toArray();
            $res = array();
            foreach ($ShopMenu as $key => $value) {
                $res[$value['id']] = $value['menu_name'];
            }
            $form->select('menu_id', '菜式分类')->options($res)->rules('required');

            /*$is_attr = [
                'on' => ['value' => 1, 'text' => '是', 'color' => 'primary'],
                'off'  => ['value' => 0, 'text' => '否', 'color' => 'default'],

            ];
            $form->switch('is_attr', '是否多规格')->states($is_attr);*/
            //$form->text('dishAttribute.attribute', '规格名称');
            $form->hasMany("dishattribute", "多规格",function ($form) {
                $form->text('attribute', '规格名称')->placeholder('如：分量');
                $form->text('spec', '规格')->placeholder('格式：辣|10,甜|5');
            });
            //$form->text('discount', '折扣');
            $form->image('thumb', '图片')->rules('required');
            $form->display('created_at', 'Created At');
            $form->display('updated_at', 'Updated At');
        });
    }
}
